package com.controller;

import com.entity.Employee;
import com.service.EmployeeInfoService;
import com.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {

    @Autowired
    private EmployeeInfoService employeeInfoService;

    @PostMapping
    public Employee create(@RequestBody Employee employee) {
        return employeeInfoService.save(employee);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable(value = "id") Integer id) {
        employeeInfoService.deleteById(id);
    }

    @PutMapping("/{id}")
    public Employee update(@PathVariable(value = "id") Integer id, @RequestBody Employee employee) {
        employee.setId(id);
        return employeeInfoService.save(employee);
    }

    @GetMapping("/{id}")
    public Employee detail(@PathVariable(value = "id") Integer id) {
        return employeeInfoService.findById(id).orElse(null);

    }

    @GetMapping("/page")
    public Page<Employee> page(@RequestParam(defaultValue = "1") int pageNum,
                                       @RequestParam(defaultValue = "10") int pageSize,
                                       @RequestParam(required = false) String name) {
        Page<Employee> page;
        if (name != null && !name.isEmpty()) {
            page = employeeInfoService.findByNameContaining(name, pageNum, pageSize);
        } else {
            page = employeeInfoService.findAll(pageNum, pageSize);
        }
        return page;
    }
}